var express = require('express');
var session = require('express-session');
var path = require('path');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
// var fs = require('fs');
/* GET users listing. */
router.get('/', function (req, res, next) {
  var db = new sqlite3.Database(path.join(__dirname, "../db/data.s3db"));
  var type = req.query.type;
  var username = req.query.username;
  if (type == 'u') { //添加一个用户
    var username = req.query.username;
    var password = req.query.password;
    try {
      db.run("INSERT INTO user VALUES('" + username + "','" + password + "')");
      res.send('1'); //插入成功
    } catch (ex) {
      console.log(ex);
    }
  } else if (type == 'c') { //添加一个商品至购物车
    var mid = req.query.mid;
    var number = req.query.number;
    var mode = req.query.mode;
    var contract = req.query.contract;
    try {
      if (mode == '0')
        db.run("INSERT INTO cart VALUES('" + username + "','" + mid + "','" + number + "','" + contract + "')");
      else if (mode == '1') {
        var number2 = req.query.number2;
        var n = parseInt(number) + parseInt(number2);
        db.run("UPDATE cart SET number ='" + n + "' WHERE username=='" + username + "' and mid=='" + mid + "'");
      }
      res.send('1');
    } catch (ex) {
      console.log(ex);
    }
  } else if (type == 'p') { //修改密码
    try {
      db.run("UPDATE user SET password ='" + req.query.new_password + "' WHERE username=='" + username + "'");
      res.send('3');
    } catch (ex) {
      console.log(ex);
    }
  }
});

module.exports = router;